# -*- coding: utf-8 -*-
import unittest
from xlrd import *
from pylab import * 
from datetime import *
from xlwt import Workbook
import os



class ExcelStats:
    def __init__(self,fileName):
        self.book = Workbook()
        self.wb = open_workbook(fileName)
        self.sheets=[]
        for s in self.wb.sheets():
            sheet=[]
            print 'Sheet:',s.name
            for row in range(s.nrows):
                values = []
                for col in range(s.ncols):
                    values.append(s.cell(row,col).value)
                sheet.append(values)
                #print values
            self.sheets.append(sheet)
        
    def getNameList(self):
        for i in range(1,len(self.sheets[0])):
            print self.sheets[0][i][0]
            
    def getBornDate(self):
        for i in range(1,len(self.sheets[0])):
            print self.sheets[0][i][2]
            
    def getCol(self,nb):
        col=[]
        for i in range(1,len(self.sheets[0])):
            col.append(self.sheets[0][i][nb])
        return col
    
    def getTitle(self,nb):
        return self.sheets[0][0][nb]
        
    def repartion(self,name):
        colone = self.searchColoneByName(name)

        category=set(self.getCol(colone))
        
        
        elements=[]   
        cardinal=[]
        table=[]
        
        table.append([self.getTitle(colone),"Repartition"])
        
        for elt in category:
            elements.append(elt)
            cardinal.append(sum((mat(self.getCol(colone))==elt)+0))
            table.append([elt,sum((mat(self.getCol(colone))==elt)+0)])
        
        #return [elements,cardinal]
        
        #self.plotCamembert(elements, cardinal, self.getTitle(colone))
        
        table.append(['total',sum(cardinal)])
        return table
    
    
    
    def searchColoneByName(self,name):
        for i in range(len(self.sheets[0][0])):
            if self.sheets[0][0][i] == name:
                return i
        print name
        assert(False)
    
    def repartitionNumber(self,name,min,max,step):
        category=arange(min,max,step)
        
        elements=[]   
        cardinal=[]
        table=[]
        
        colone = self.searchColoneByName(name)
        
        table.append([self.getTitle(colone),"Repartition"])
        
        for elt in category:
            elements.append(elt)
            
            col=array(self.getCol(colone))
            
            card=sum(((col>=elt)+0)*((col<((elt+step))+0)))
            
            cardinal.append(card)
            table.append([str(elt)+'-'+str(elt+step-1),card])
        
        #return [elements,cardinal]
        table.append(['total',sum(cardinal)])
        return table
          
        
           
    def printTable(self,tab):
               
        sheet = self.book.add_sheet(tab[0][0].replace('/','-'))
        
        for i in range(len(tab)):
            for j in range(len(tab[i])):
                sheet.write(i,j,tab[i][j])
                
        #self.book.save(os.environ["USERPROFILE"]+'/Desktop/Statistiques.xls')
        self.book.save('Statistiques.xls')
        
    def plotCamembert(self,labels,fracs,title):
        # make a square figure and axes
        figure(1, figsize=(6,6))
        ax = axes([0.1, 0.1, 0.8, 0.8])
  
        pie(fracs,  labels=labels, autopct='%1.1f%%', shadow=True)
    
        show()
          

class Test(unittest.TestCase):
    def testName(self):
        stats=ExcelStats('Stats_RAM-RAV.xls')
        
        stats.printTable(stats.repartitionNumber("Age",20,70,10))
        
        stats_voulue=["Sexe","Orienteur","Provenance","DESTINATION","Réhospitalisation","H.Séquentielle","Katimavic","Travail","GEM","HDJ-CATTP","Tuteur-Curateur","Passage infirmier","SAVS","CCAS (Repas)","Aide ménagère"]
               
        for i in range(len(stats_voulue)):                               
            stats.printTable(stats.repartion(stats_voulue[i]))

         
if __name__ == "__main__":
    unittest.main()